package com.aibaixun.system.service.impl;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.lang.tree.Tree;
import cn.hutool.json.JSONUtil;
import com.aibaixun.common.core.domain.R;
import com.aibaixun.common.utils.BeanCopyUtils;
import com.aibaixun.system.domain.DicmAddress;
import com.aibaixun.system.domain.DicmCabinet;
import com.aibaixun.system.domain.PostureDevice;
import com.aibaixun.system.domain.dto.BindDeviceDto;
import com.aibaixun.system.domain.dto.IndexStatisticsDto;
import com.aibaixun.system.domain.vo.CabinetUsageSituationVo;
import com.aibaixun.system.domain.vo.QueryDeviceTreeVo;
import com.aibaixun.system.domain.vo.QueryDeviceVo;
import com.aibaixun.system.mapper.DicmCabinetMapper;
import com.aibaixun.system.service.DicmAddressService;
import com.aibaixun.system.service.DicmCabinetService;
import com.aibaixun.system.service.PostureDeviceService;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.stream.Collectors;

/**
 * <b>DicmCabinetServiceImpl</b>
 *
 * @description: DicmCabinetServiceImpl <br>
 * @date: 2024/7/18 12:03 <br>
 * @author: lhm <br>
 * @version: 1.0 <br>
 */

@Service
public class DicmCabinetServiceImpl extends ServiceImpl<DicmCabinetMapper, DicmCabinet> implements DicmCabinetService {
    private static final Logger logger = LoggerFactory.getLogger(DicmCabinetServiceImpl.class);

//    @Autowired
//    private DicmAddressService dicmAddressService;



    @Override
    public void savecabinetList(List<DicmCabinet> cabinetList) {
        cabinetList.forEach(item -> {
            QueryWrapper queryWrapper = new QueryWrapper();
            queryWrapper.eq("address_id",item.getAddressId());
            DicmCabinet dicmCabinet = baseMapper.selectOne(queryWrapper);
            if (null == dicmCabinet){
                baseMapper.insert(item);
            }
        });
    }

    @Override
    public List<QueryDeviceTreeVo> queryCabinetList(String parentId) {
        return baseMapper.queryCabinetList(parentId);
    }

    @Override
    public List<DicmCabinet> queryCabinetListById(List<String> addressIdList) {
        return baseMapper.queryCabinetListById(addressIdList);
    }

    @Override
    public boolean updateCabinet(BindDeviceDto dto) {
        UpdateWrapper updateWrapper = new UpdateWrapper();
        updateWrapper.eq("address_id",dto.getId());
        updateWrapper.set("ue_id",dto.getUeId());
        int update = baseMapper.update(null, updateWrapper);
        if (1 == update){
            return true;
        }
        return false;
    }

    @Override
    public void updateCabinetUeId(BindDeviceDto dto) {
        QueryWrapper queryWrapper = new QueryWrapper();
        queryWrapper.eq("parent_id",dto.getId());
        List<DicmCabinet> cabinetList = baseMapper.selectList(queryWrapper);
        if (CollectionUtil.isNotEmpty(cabinetList)){
            cabinetList.forEach(item -> {
                if (StringUtils.isNotEmpty(item.getUeId())){
                    String ueId = "";
                    String[] split = item.getUeId().split("-");
                    for (int i = 0; i < split.length; i++) {
                        if (i < 3){
                            ueId = ueId+split[i]+"-";
                        }else if (i == 3){
                            ueId = ueId+split[i];
                        }
                    }

                    String newUeId = item.getUeId().replace(ueId, dto.getUeId());
                    item.setUeId(newUeId);

//                    String patternString = "^(\\d+)-(\\d+)-(\\d+)-(\\d+)";
//                    Pattern pattern = Pattern.compile(patternString);
//                    Matcher matcher = pattern.matcher(item.getUeId());
//                    if (matcher.find()) {
//                        String oldUeId = matcher.group();
//                        String ueId = item.getUeId();
//                        String newUeId = ueId.replace(oldUeId, dto.getUeId());
//                        item.setUeId(newUeId);
//                    }
                }else {
                    item.setUeId(dto.getUeId()+"-"+item.getCabinetName());
                }
                baseMapper.updateById(item);
            });
        }
    }

    @Override
    public QueryDeviceVo queryByRoomUeId(String cabinetId) {
        return baseMapper.queryByRoomUeId(cabinetId);
    }

    @Override
    public void resetUeId() {
        QueryWrapper queryWrapper = new QueryWrapper();
        queryWrapper.eq("ue_id","空");
        List<DicmCabinet> cabinetList = baseMapper.selectList(queryWrapper);
        if (CollectionUtil.isNotEmpty(cabinetList)){
            cabinetList.forEach(item -> {
                item.setUeId("");
                baseMapper.updateById(item);
            });
        }
    }

//    @Override
//    public CabinetUsageSituationVo getCabinetTotal(IndexStatisticsDto dto) {
//        CabinetUsageSituationVo vo = new CabinetUsageSituationVo();
//        R<List<Tree<String>>> tree = dicmAddressService.getTree(new DicmAddress());
//        List<Tree<String>> data = tree.getData();
//        logger.info("返回资产树结果:{}"+ JSONUtil.parse(data));
//        Map<String,List<String>> map = new HashMap<>();
//        List<Tree<String>> treeList = (List<Tree<String>>)data.get(0).get("children");
//        List<String> addressIdList = new ArrayList<>();
//        if (1 == dto.getType()){
//            treeList.forEach(item -> {
//                addressIdList.add(item.get("id").toString());
//            });
//        }else if (2 == dto.getType()){
//            treeList.forEach(item -> {
//                if (dto.getAddressId().equals(item.get("id").toString())){
//                    List<Tree<String>> treeList1 = (List<Tree<String>>)item.get("children");
//                    treeList1.forEach(value -> {
//                        addressIdList.add(value.get("id").toString());
//                    });
//                }
//            });
//        }
//        List<DicmCabinet> cabinetList = baseMapper.queryCabinetListById(addressIdList);
//        if (CollectionUtil.isNotEmpty(cabinetList)){
//            Integer capacity = 0;
//            Integer used = 0;
//            for (DicmCabinet dicmCabinet : cabinetList) {
//                capacity = capacity + Integer.parseInt(dicmCabinet.getUsum());
//            }
//            vo.setCapacity(capacity);
//            List<String> addressNameList = cabinetList.stream().map(DicmCabinet::getAddressId).collect(Collectors.toList());
//            List<PostureDevice> deviceList = postureDeviceService.queryDeviceListByCabinet(addressNameList);
//            if (CollectionUtil.isNotEmpty(deviceList)){
//                Map<String, List<PostureDevice>> map1 = deviceList.stream().collect(Collectors.groupingBy(PostureDevice::getCabinetNum));
//                for (String addressName : addressNameList) {
//                    if (CollectionUtil.isNotEmpty(map1.get(addressName))){
//                        List<PostureDevice> postureDeviceList = map1.get(addressName);
//                        for (PostureDevice postureDevice : postureDeviceList) {
//                            used = used + postureDevice.getUuse();
//                        }
//                    }
//                }
//                vo.setUsed(used);
//                vo.setRemaining(capacity - used);
//                vo.setCabinetRate(new BigDecimal(used).divide(new BigDecimal(capacity),2, RoundingMode.HALF_UP));
//            }
//        }
//
//        return vo;
//    }
}

